package com.hylanda.processors.imagerecognition.util;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@SuppressWarnings("restriction")
public class Base64ImageUtil {

	
	 //base64字符串转化成图片  
    public static boolean GenerateImage(String imgStr)  
    {   //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
            return false;  
        BASE64Decoder decoder = new BASE64Decoder();  
        try   
        {  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
            //生成jpeg图片  
            String imgFilePath = "D:\\new.jpg";//新生成的图片  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            return false;  
        }  
    }  
    
    public static String GetUrlImageToBase64(String strUrl) {
       
        URL url = null;
        try {
            url = new URL(strUrl);
        } catch (MalformedURLException e2) {
            return "下载图片异常，新建URL失败";
        }
        InputStream is = null;
        try {
            is = url.openStream();
            return readInfoStreamToBytes(is);
        } catch (IOException e1) {
            return "下载图片异常";
        }
    }
    public static String readInfoStreamToBytes(InputStream is) {
        if (is == null) {
            return "输入流为null";
        }

        // 字节数组
        byte[] bCache = new byte[2048];
        int readSize = 0;// 每次读取的字节长度
        ByteArrayOutputStream infoStream = new ByteArrayOutputStream();
        try {
            // 一次性读取2048字节
            while ((readSize = is.read(bCache)) > 0) {
                
                // 将bcache中读取的input数据写入infoStream
                infoStream.write(bCache, 0, readSize);
            }
        } catch (IOException e1) {
            return "输入流读取异常";
        } finally {
            try {
                is.close();
            } catch (IOException e) {
               // LOGGER.error("输入流关闭异常");
            }
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(infoStream.toByteArray());
    }
	public static void main(String[] args) {
		String result = GetUrlImageToBase64("http://p1.img.cctvpic.com/cportal/img/photoAlbum/page/performance/img/2018/2/25/1519549863706_2_603x452.jpg");
		System.out.println(result);
		GenerateImage(result);
	}
}
